package ran.friend.manager;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.PageHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import ran.constants.Constants;
import ran.constants.RedisCacheConstants;
import ran.enums.ExamType;
import ran.enums.ResultCode;
import ran.exception.ServiceException;
import ran.friend.domain.exam.dto.ExamQueryDTO;
import ran.friend.domain.exam.entity.Exam;
import ran.friend.domain.exam.entity.ExamQuestion;
import ran.friend.domain.exam.vo.ExamVO;
import ran.friend.domain.user.entity.UserExam;
import ran.friend.mapper.exam.ExamMapper;
import ran.friend.mapper.exam.ExamQuestionMapper;
import ran.friend.mapper.user.UserExamMapper;
import ran.redis.service.RedisService;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: ran
 * Date: 2025-11-10
 * Time: 17:18
 */
@Component
public class ExamRedisCacheManager {

    private static final Logger log = LoggerFactory.getLogger(ExamRedisCacheManager.class);
    @Autowired
    private RedisService redisService;

    @Autowired
    private ExamMapper examMapper;

    @Autowired
    private UserExamMapper userExamMapper;

    @Autowired
    private ExamQuestionMapper examQuestionMapper;

    private Integer size;
    // 获取Redis中数据量
    public Long getListSize(Integer examListType, Long userId) {
        // 判断要查询 未发布竞赛 还是 历史竞赛 还是 我的竞赛列表
        String examListKey = getExamListKey(examListType, userId);
        return size != null ? size : redisService.getListSize(examListKey);
    }
    public Long getExamQuestionListSize(Long examId) {
        String examQuestionListKey = getExamQuestionListKey(examId);
        return redisService.getListSize(examQuestionListKey);
    }

    // 获取竞赛第一道题目
    public Long getFirstQuestion(Long examId) {
        return redisService.indexForList(getExamQuestionListKey(examId), 0, Long.class);
    }

    // 获取竞赛上一道题目
    public Long preQuestion(Long examId, Long questionId) {
        Long index = redisService.indexOfForList(getExamQuestionListKey(examId), questionId);
        // 第一道题目, 不可向前切换
        if (index == 0) {
            throw new ServiceException(ResultCode.FAILED_FIRST_QUESTION);
        }
        return redisService.indexForList(getExamQuestionListKey(examId),index - 1,Long.class);
    }
    // 获取竞赛下一道题目
    public Long nextQuestion(Long examId, Long questionId) {
        Long index = redisService.indexOfForList(getExamQuestionListKey(examId), questionId);
        Long lastIndex = getExamQuestionListSize(examId) - 1;
        log.info("lastIndex:{}",lastIndex);
        // 最后一道题目, 不可向后切换
        if (index >= lastIndex) {
            throw new ServiceException(ResultCode.FAILED_LAST_QUESTION);
        }
        return redisService.indexForList(getExamQuestionListKey(examId),index + 1,Long.class);
    }

    // 刷新Redis缓存
    public void refreshCache(Integer examListType, Long userId) {
        List<Exam> list = new ArrayList<>();
        if (ExamType.EXAM_UNFINISHED_LIST.getType().equals(examListType)) {
            list = examMapper.selectList(new LambdaQueryWrapper<Exam>()
                    .select(Exam::getExamId,Exam::getTitle,Exam::getStartTime,Exam::getEndTime)
                    .eq(Exam::getStatus, Constants.TRUE)
                    .gt(Exam::getEndTime, LocalDateTime.now()) // 未完赛, 结束时间大于当前时间
                    .orderByDesc(Exam::getCreateTime));
        }else if (ExamType.EXAM_FINISHED_LIST.getType().equals(examListType)) {
            list = examMapper.selectList(new LambdaQueryWrapper<Exam>()
                    .select(Exam::getExamId,Exam::getTitle,Exam::getStartTime,Exam::getEndTime)
                    .eq(Exam::getStatus, Constants.TRUE)
                    .le(Exam::getEndTime, LocalDateTime.now()) // 历史竞赛, 结束时间小于等于当前时间
                    .orderByDesc(Exam::getCreateTime));
        }else if (ExamType.USER_EXAM_LIST.getType().equals(examListType)) {
            List<ExamVO> examVOList = userExamMapper.selectUserExamList(userId);
            list = BeanUtil.copyToList(examVOList,Exam.class);
        }

        // 数据为空, 直接返回
        if (CollectionUtil.isEmpty(list)) {
            return;
        }
        // 竞赛详细信息的map
        Map<String, Exam> examMap = new HashMap<>();
        // 未完赛信息的 examId集合
        List<Long> examIdList = new ArrayList<>();
        for (Exam exam : list) {
            examMap.put(getDetailKey(exam.getExamId()),exam);
            examIdList.add(exam.getExamId());
        }
        // 批量添加/更新Redis中竞赛详细信息, 这里因为我们是用的是String类型, key一样时自动覆盖, 所以不用提前删除
        redisService.multiSet(examMap);
        // 先清楚旧的数据, 再更新新的数据, 这里存的是 竞赛id
        redisService.deleteObject(getExamListKey(examListType,userId));
        redisService.rightPushAll(getExamListKey(examListType,userId),examIdList);// 尾差, 因为我们查出来的数据是排好序的
    }

    // 刷新竞赛的题目列表缓存
    public void refreshExamQuestionCache(Long examId) {
        List<ExamQuestion> examQuestionList = examQuestionMapper.selectList(new LambdaQueryWrapper<ExamQuestion>()
                .select(ExamQuestion::getQuestionId)
                .eq(ExamQuestion::getExamId, examId)
                .orderByAsc(ExamQuestion::getQuestionOrder));
        if (CollectionUtil.isEmpty(examQuestionList)) {
            return;
        }
        List<Long> questionIdList = examQuestionList.stream().map(ExamQuestion::getQuestionId).toList();
        redisService.rightPushAll(getExamQuestionListKey(examId),questionIdList);
    }


    // 获取竞赛列表 或 我的竞赛列表
    public List<ExamVO> getExamVOList(ExamQueryDTO examQueryDTO, Long userId) {
        // Redis List类型的分页需要知道准确下标
        int start = (examQueryDTO.getPageNum() - 1) * examQueryDTO.getPageSize();
        int end = start + examQueryDTO.getPageSize() - 1;// 求得是下标,需要 - 1
        List<Long> examIdList = redisService.getCacheListByRange(getExamListKey(examQueryDTO.getType(),userId), start, end, Long.class);

        // 从Redis获取 examVOList, 一旦有问题会获取到null
        List<ExamVO> examVOList = assembleExamVOList(examIdList);

        if (CollectionUtil.isEmpty(examVOList)) {
            // 从数据库中查询数据
            examVOList =  getListByDB(examQueryDTO, userId);

            // 刷新Redis中的缓存
            refreshCache(examQueryDTO.getType(),userId);
        }
        // 正确从Redis中查询到了数据
        // 这里查询到数据之后, 再进行竞赛时间条件的筛选
        List<ExamVO> newExamVOList = new ArrayList<>();
//        System.out.println(examQueryDTO.getEndTime());
//        System.out.println(examQueryDTO.getStartTime());
        if (examQueryDTO.getStartTime() != null && examQueryDTO.getEndTime() != null) {
            for (ExamVO examVO : examVOList) {
                if (examVO.getStartTime().isAfter(examQueryDTO.getStartTime())
                        && examVO.getEndTime().isBefore(examQueryDTO.getEndTime())) {
                    newExamVOList.add(examVO);
                }
            }
            size = newExamVOList.size();
        }else {
            size = null;
        }
//        System.out.println(newExamVOList);
        return examQueryDTO.getStartTime() != null && examQueryDTO.getEndTime() != null ? newExamVOList : examVOList;
    }

    // 获取Redis中的用户竞赛id集合
    public List<Long> getAllUserExamIdList(Long userId) {
        String userExamListKey = getUserExamListKey(userId);
        // 先去Redis中查询这个list
        List<Long> userExamIdList = redisService.getCacheListByRange(userExamListKey, 0, -1, Long.class);
        // 不为空直接返回
        if (CollectionUtil.isNotEmpty(userExamIdList)) {
            return userExamIdList;
        }
        // 为空的话去数据库中查询
        List<UserExam> userExamList = userExamMapper.selectList(new LambdaQueryWrapper<UserExam>().eq(UserExam::getUserId, userId));
        // 数据库中查询的也是空, 那么直接返回null
        if (CollectionUtil.isEmpty(userExamList)) {
            return null;
        }
        // 刷新缓存
        refreshCache(ExamType.USER_EXAM_LIST.getType(),userId);
        return userExamList.stream().map(UserExam::getUserId).collect(Collectors.toList());
    }

    private List<ExamVO> assembleExamVOList(List<Long> examIdList) {
        if (CollectionUtil.isEmpty(examIdList)) {
            // Redis数据有问题, 返回null,为刷新内存提供条件
            return null;
        }
        // 将id封装到后去详细信息的key的集合里
        List<String> detailKeyList = new ArrayList<>();
        for (Long examId : examIdList) {
            detailKeyList.add(getDetailKey(examId));
        }
        List<ExamVO> examVOList = redisService.multiGet(detailKeyList, ExamVO.class);
        // 把一些为null的数据清空, 防止在竞赛id存进去了, 竞赛详细信息没有存进去
        CollUtil.removeNull(examVOList);
        if (CollectionUtil.isEmpty(examVOList) || examIdList.size() != examVOList.size()) {
            // Redis数据有问题, 返回null,为刷新内存提供条件
            return null;
        }
        return examVOList;
    }

    private List<ExamVO> getListByDB(ExamQueryDTO examQueryDTO, Long userId) {
        // 查询的数据为空, 那么聪数据库中查询
        PageHelper.startPage(examQueryDTO.getPageNum(),examQueryDTO.getPageSize());// 引入分页插件,可以自动在查询条件下加入分页SQL语句
        // 如果是0/1去examMapper中查, 如果是2去我的竞赛列表查
        if (ExamType.USER_EXAM_LIST.getType().equals(examQueryDTO.getType())) {
            // 我的竞赛列表
            return userExamMapper.selectUserExamList(userId);
        }else {
            // 历史竞赛/ 未完赛
            return examMapper.selectExamList(examQueryDTO);
        }
    }

    // 存储报名的竞赛列表
    public void saveUserExam(Long userId, Long examId) {
        String userExamListKey = getUserExamListKey(userId);
        redisService.leftPushForList(userExamListKey,examId);
    }

    private String getUserExamListKey(Long userId) {
        return RedisCacheConstants.USER_EXAM_LIST + userId;
    }

    private String getExamListKey(Integer examListType, Long userId) {
        if (ExamType.EXAM_UNFINISHED_LIST.getType().equals(examListType)) {
            return RedisCacheConstants.EXAM_UNFINISHED_LIST;
        }else if (ExamType.EXAM_FINISHED_LIST.getType().equals(examListType)) {
            return RedisCacheConstants.EXAM_HISTORY_LIST;
        }else if (ExamType.USER_EXAM_LIST.getType().equals(examListType)) {
            return getUserExamListKey(userId);
        }
        return "";
    }

    private String getDetailKey(Long examId) {
        return RedisCacheConstants.EXAM_DETAIL + examId;
    }

    private String getExamQuestionListKey(Long examId) {
        return RedisCacheConstants.EXAM_QUESTION_LIST + examId;
    }



}
